package cn.francis.framework.handler;

import cn.francis.common.enums.CommonErrorCode;
import cn.francis.common.exception.BusinessException;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.ClassUtils;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

/**
 * @author 张俊辉
 */

@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
    /**
     * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
     *
     * @param fieldName  属性名
     * @param fieldVal   属性值
     * @param metaObject MetaObject
     * @param isCover    是否覆盖原有值,避免更新操作手动入参
     */
    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) {
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        Object userSetValue = metaObject.getValue(fieldName);
        String userSetValueStr = StrUtil.str(userSetValue, Charset.defaultCharset());
        if (CharSequenceUtil.isNotBlank(userSetValueStr) && !isCover) {
            return;
        }
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        log.info("开始插入填充，时间：{}", now);
        // todo 修改用户
        fillValIfNullByName("createBy", "junhui", metaObject, false);
//        this.strictInsertFill(metaObject, "createBy", String.class, "junhui");
        fillValIfNullByName("createTime", now, metaObject, false);
        fillValIfNullByName("updateBy", "junhui", metaObject, false);
        fillValIfNullByName("updateTime", now, metaObject, false);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            LocalDateTime now = LocalDateTime.now();
            log.info("开始更新填充，时间：{}", now);
            fillValIfNullByName("updateTime", now, metaObject, true);
            fillValIfNullByName("updateBy", "junhui", metaObject, true);
        } catch (Exception e) {
            throw new BusinessException(CommonErrorCode.HTTP_UNAUTHORIZED.getCode(), "自动注入异常 => " + e.getMessage());
        }
    }
}
